package com.bwie.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class DriverWebSocketHandler extends TextWebSocketHandler {

    // 存储所有上报信息的司机信息（线程安全）
    // key = driverId
    // value = DriverInfoVo
    private static final ConcurrentHashMap<String, WebSocketSession> sessionsMap = new ConcurrentHashMap<>();

    // 存储所有活跃的WebSocket会话（线程安全）
    private static final Set<WebSocketSession> sessions =
            Collections.synchronizedSet(new HashSet<>());

    // 客户端连接成功时触发
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        System.out.println("新客户端连接，当前在线数：" + sessions.size());
        String id = session.getId();
        System.out.println("id：" + id);
        session.sendMessage(new TextMessage("连接成功！"));
    }

    // 接收客户端消息时触发
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String clientMessage = message.getPayload();
        System.out.println("收到消息：" + clientMessage);

        // 示例：向所有客户端广播消息
        broadcast("服务器收到：" + clientMessage);
    }

    // 客户端断开连接时触发
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        System.out.println("客户端断开，当前在线数：" + sessions.size());
    }



    // 广播消息给所有在线客户端
    private void broadcast(String message) throws IOException {
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) { // 确保连接未关闭
                session.sendMessage(new TextMessage(message));
            }
        }
    }
}
